﻿using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 绘制Physics的样子方便调试
    /// </summary>
    public class PhysicsDraw : MonoBehaviour
    {
        public static PhysicsDraw mI;

        public static PhysicsDraw I
        {
            get
            {
                if (mI == null)
                {
                    GameObject go = new GameObject("PhysicsDraw");
                    mI = go.AddComponent<PhysicsDraw>();
                    DontDestroyOnLoad(mI);
                }

                return mI;
            }
        }

        public bool isSphereCast;
        public float sphereRadius;
        public float maxDistance;

        //方块
        public bool isBoxCast;
        public Vector3 halfExtens;
        public Quaternion boxQuater;

        public Vector3 origin;
        public Vector3 direction;
        public LayerMask layerMask;

        private float currentHitDistance;
        private GameObject currentHitObject;

        public void Start()
        {
        }

        public void Update()
        {
            origin = transform.position;
            direction = transform.forward;

            SphereCastSus();
            BoxCastSus();
        }

        private void BoxCastSus()
        {
            if (!isSphereCast)
            {
                return;
            }

            RaycastHit hit;
            if (Physics.BoxCast(origin, halfExtens, direction, out hit, boxQuater, maxDistance, layerMask,
                QueryTriggerInteraction.UseGlobal))
            {
                currentHitObject = hit.transform.gameObject;
                currentHitDistance = hit.distance;
            }
            else
            {
                currentHitObject = null;
                currentHitDistance = maxDistance;
            }
        }


        private void SphereCastSus()
        {
            if (!isSphereCast)
            {
                return;
            }

            RaycastHit hit;
            if (Physics.SphereCast(origin, sphereRadius, direction, out hit, maxDistance, layerMask,
                QueryTriggerInteraction.UseGlobal))
            {
                currentHitObject = hit.transform.gameObject;
                currentHitDistance = hit.distance;
            }
            else
            {
                currentHitObject = null;
                currentHitDistance = maxDistance;
            }
        }


        private void OnDrawGizmos()
        {
            Vector3 endPos = origin + direction * currentHitDistance;
            Gizmos.color = Color.red;
            Debug.DrawLine(origin, endPos);

            if (!isSphereCast)
            {
                Gizmos.DrawWireSphere(endPos, sphereRadius);
            }

            if (!isSphereCast)
            {
                Gizmos.DrawWireSphere(endPos, sphereRadius);
            }
        }
    }
}